package com.ocl.www.websocket;

import com.ocl.www.utils.JDBCUntil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import javax.websocket.*;
import javax.websocket.server.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
//import java.util.concurrent.CopyOnWriteArraySet;

//import static org.eclipse.jdt.internal.compiler.parser.Parser.name;
//
//ws://127.0.0.1:8087/Demo1/ws/张三

@ServerEndpoint(value = "/websocket")
public class WSServer {


	private RemoteEndpoint.Basic remote;

//	private static int onlineCount = 0;
//
//	private static CopyOnWriteArraySet<WSServer> webSocketSet = new CopyOnWriteArraySet<>();

	private Session session;

	//连接打开时执行
	@OnOpen
	public void onOpen(Session session) {
		this.session = session;
//		remote = this.session.getBasicRemote();
		System.out.println("服务端onOpen："+session.getId());
		try {
			remote = session.getBasicRemote();
			session.getBasicRemote().sendText("你好client，我是服务端！");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	//收到消息时执行
	@OnMessage
	public String onMessage(String message, Session session) throws IOException {

		Map<String, String> map = new HashMap<>();
		JSONObject resultjson = new JSONObject();
//		System.out.println(message+" "+session.getId());
//		JSONObject jsonObject = JSONObject.fromObject("{senderId:'15815006577',reciverId:'0',createTime:'2017-06-17 23:11:13'}");
		JSONObject jsonObject = JSONObject.fromObject(message);
		String senderId = jsonObject.get("senderId").toString();
		String reciverId = jsonObject.get("reciverId").toString();
		String isfirst = jsonObject.get("isfirst").toString();
		String createTime = "";
		if (isfirst.equals("n")){
			createTime = jsonObject.get("createTime").toString();
		}


		try {
            Connection con = JDBCUntil.getConnection();
            //2.创建statement类对象，用来执行SQL语句！！
            Statement statement = con.createStatement();
            //要执行的SQL语句
            String sql = null;

            if ("0".equals(reciverId)){
				if ("n".equals(isfirst)){
					sql = "SELECT c.user_name AS userName ,c.user_img AS userImg, b.id AS id,b.sender_id AS senderId,b.reciver_id AS reciverId,b.create_time AS createTime,b.content AS content " +
							" FROM ly_userchat b ,ly_user c  WHERE  b.`sender_id` = c.user_id AND  (b.reciver_id=0 OR b.sender_id=0) AND b.create_time > '" + createTime +
							"' ORDER BY b.create_time ASC LIMIT 20";
				}else{
					sql = "SELECT c.user_name AS userName ,c.user_img AS userImg, b.id AS id,b.sender_id AS senderId,b.reciver_id AS reciverId,b.create_time AS createTime,b.content AS content "+
							" FROM ly_userchat b ,ly_user c "+
							" WHERE  b.`sender_id` = c.user_id AND (b.reciver_id=0 OR b.sender_id=0)  ORDER BY b.create_time DESC LIMIT 20";
				}
			}else{

				if ("n".equals(isfirst)){
					sql = "SELECT c.user_name AS userName ,c.user_img AS userImg,  b.id AS id,b.sender_id AS senderId,b.reciver_id AS reciverId,b.create_time AS createTime,b.content AS content " +
							" FROM (SELECT * FROM ly_userchat WHERE sender_id = '" + senderId + "' AND reciver_id =  '" + reciverId + "'" +
							" UNION SELECT * FROM ly_userchat WHERE sender_id = '" + reciverId + "' AND reciver_id = '" + senderId + "') b ,ly_user c " +
							" WHERE b.`sender_id` = c.user_id  AND b.create_time > '" + createTime + "' ORDER BY b.create_time ASC  LIMIT 20";
				}else{
					sql = "SELECT c.user_name AS userName ,c.user_img AS userImg,  b.id AS id,b.sender_id AS senderId,b.reciver_id AS reciverId,b.create_time AS createTime,b.content AS content " +
							" FROM (SELECT * FROM ly_userchat  WHERE sender_id = '" + senderId + "' AND reciver_id =  '" + reciverId + "'" +
							" UNION SELECT * FROM ly_userchat  WHERE sender_id = '" + reciverId + "' AND reciver_id = '" + senderId + "') b ,ly_user c WHERE  b.`sender_id` = c.user_id " +
							" ORDER BY b.create_time DESC LIMIT 20";
				}

			}

            //3.ResultSet类，用来存放获取的结果集！！
            ResultSet rs = null;
            rs = statement.executeQuery(sql);
            JSONArray lyUserchatjsonarr = new JSONArray();
            while (rs.next()) {

				JSONObject lyusercharjson = new JSONObject();
				lyusercharjson.put("userImg",rs.getString("userImg"));
				lyusercharjson.put("userName",rs.getString("userName"));
				lyusercharjson.put("content",rs.getString("content"));
				lyusercharjson.put("createTime",rs.getTimestamp("createTime").toString());
				lyusercharjson.put("reciverId",rs.getString("reciverId"));
				lyusercharjson.put("senderId",rs.getString("senderId"));
				lyusercharjson.put("id",rs.getInt("id"));

				lyUserchatjsonarr.add(lyusercharjson);
            }

			if ("y".equals(isfirst)) {
				JSONArray lyUserchatjsonarr2 = new JSONArray();
				for (int i = lyUserchatjsonarr.size() - 1; i > 0; i--) {
					lyUserchatjsonarr2.add(lyUserchatjsonarr.get(i));
				}
				lyUserchatjsonarr = lyUserchatjsonarr2;
				lyUserchatjsonarr2 = null;
			}

			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

//            System.out.println("你有" + c + "条信息未读！");
//            System.out.println("====" + String.valueOf(lyUserchatjsonarr));

            resultjson.put("status","s");
			resultjson.put("info",lyUserchatjsonarr.toString());

//				remote.sendText("hello! 我是服务端");
		}catch (NullPointerException e) {
			resultjson.put("status","s");
			resultjson.put("info",e.getMessage());
        } catch (ClassNotFoundException e) {
			resultjson.put("status","s");
			resultjson.put("info",e.getMessage());
        } catch (SQLException e) {
			e.printStackTrace();
		}

		if(!session.isOpen())session.close();
//		System.out.println("Connected ... "+resultjson);
		remote.sendText(resultjson.toString());

		return null;
	}


	//连接关闭时执行
	@OnClose
	public void onClose(Session session, CloseReason closeReason) {
//		try {
//			session.close();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		System.out.println(String.format("Session %s closed because of %s", session.getId(), closeReason));
	}

	//连接错误时执行
	@OnError
	public void onError(Throwable t) {
		t.printStackTrace();
	}


}
